/*
 * Copyright (c) 2010-2020 Belledonne Communications SARL.
 *
 * This file is part of linphone-android
 * (see https://www.linphone.org).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.newlink.building.activities.main.dialer.viewmodels

import android.content.Context
import android.os.Vibrator
import android.text.Editable
import android.text.TextUtils
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.lifecycle.MutableLiveData
import com.newlink.building.NL_App.Companion.context
import com.newlink.building.NL_App.Companion.coreContext
import com.newlink.building.NL_App.Companion.corePreferences
import com.newlink.building.R
import com.newlink.building.activities.main.dialer.Module_Phone_DialerHistoryTabClickListener
import com.newlink.building.activities.main.dialer.Module_Phone_NumpadDigitListener
import com.newlink.building.activities.main.history.data.Module_Phone_GroupedCallLogData
import com.newlink.building.activities.main.viewmodels.Module_Phone_LogsUploadViewModel
import com.newlink.building.compatibility.Module_Phone_Compatibility
import com.newlink.building.utils.Module_Phone_Event
import org.linphone.core.Account
import org.linphone.core.AccountListenerStub
import org.linphone.core.Call
import org.linphone.core.Core
import org.linphone.core.CoreListenerStub
import org.linphone.core.ProxyConfig
import org.linphone.core.RegistrationState
import org.linphone.core.tools.Log
import java.util.Timer
import java.util.TimerTask

class Module_Phone_DialerViewModel : Module_Phone_LogsUploadViewModel() {

    val mSipIconResource = MutableLiveData<Int>()

    val mSipIconContentDescription = MutableLiveData<String>()

    val mSipLine = MutableLiveData<String>()

    // 0全部，1去电，2未接
    val mCallLogsState = MutableLiveData<Int>()

    val mCallLogsListData = MutableLiveData<ArrayList<Module_Phone_GroupedCallLogData>>()

    val mOutgoingCallLogsListData = MutableLiveData<ArrayList<Module_Phone_GroupedCallLogData>>()

    val mMissedCallLogsListData = MutableLiveData<ArrayList<Module_Phone_GroupedCallLogData>>()

    val mCallLogsSearchListData = MutableLiveData<ArrayList<Module_Phone_GroupedCallLogData>>()

    val mShowDialerPlate = MutableLiveData<Boolean>()

    val mDialerEditText = MutableLiveData<EditText>()

    val enteredUri = MutableLiveData<String>()

    val atLeastOneCall = MutableLiveData<Boolean>()

    val transferVisibility = MutableLiveData<Boolean>()

    val showPreview = MutableLiveData<Boolean>()

    val showSwitchCamera = MutableLiveData<Boolean>()

    val autoInitiateVideoCalls = MutableLiveData<Boolean>()

    val updateAvailableEvent: MutableLiveData<Module_Phone_Event<String>> by lazy {
        MutableLiveData<Module_Phone_Event<String>>()
    }

    private val vibrator =
        coreContext.context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator

    private var addressWaitingNetworkToBeCalled: String? = null
    private var timeAtWitchWeTriedToCall: Long = 0

    private var enteredUriCursorPosition: Int = 0

    val onDialerHistoryTabClick: Module_Phone_DialerHistoryTabClickListener =
        object : Module_Phone_DialerHistoryTabClickListener {
            override fun handleClick(historyState: Int) {
                mCallLogsState.value = historyState
            }
        }

    val onKeyClick: Module_Phone_NumpadDigitListener = object : Module_Phone_NumpadDigitListener {
        override fun handleClick(key: Char) {
            if (mDialerEditText.value?.selectionStart == null) {
                enteredUriCursorPosition = 0
            } else {
                enteredUriCursorPosition = mDialerEditText.value?.selectionStart!!
            }
            if (enteredUriCursorPosition < 0) enteredUriCursorPosition = 0

            val sb: StringBuilder = StringBuilder(enteredUri.value)
            try {
                sb.insert(enteredUriCursorPosition, key.toString())
            } catch (ioobe: IndexOutOfBoundsException) {
                sb.insert(sb.length, key.toString())
            }
            enteredUri.value = sb.toString()

            if (vibrator.hasVibrator() && corePreferences.dtmfKeypadVibration) {
                Module_Phone_Compatibility.eventVibration(vibrator)
            }
        }

        override fun handleLongClick(key: Char): Boolean {
            if (mDialerEditText.value?.selectionStart == null) {
                enteredUriCursorPosition = 0
            } else {
                enteredUriCursorPosition = mDialerEditText.value?.selectionStart!!
            }
            if (enteredUriCursorPosition < 0) enteredUriCursorPosition = 0
//            if (key == '1') {
//                val voiceMailUri = corePreferences.voiceMailUri
//                if (voiceMailUri != null) {
//                    coreContext.startCall(voiceMailUri)
//                }
//            } else {
            val sb: StringBuilder = StringBuilder(enteredUri.value)
            try {
                sb.insert(enteredUriCursorPosition, key.toString())
            } catch (ioobe: IndexOutOfBoundsException) {
                sb.insert(sb.length, key.toString())
            }
            enteredUri.value = sb.toString()
//            }
            return true
        }
    }

    val accountListener: AccountListenerStub = object : AccountListenerStub() {
        override fun onRegistrationStateChanged(
            account: Account,
            state: RegistrationState,
            message: String
        ) {
            updateSipIconResource()
        }
    }

    private val listener = object : CoreListenerStub() {

        override fun onCallStateChanged(
            core: Core,
            call: Call,
            state: Call.State,
            message: String
        ) {
            atLeastOneCall.value = core.callsNb > 0
        }

        override fun onRegistrationStateChanged(
            core: Core,
            proxyConfig: ProxyConfig,
            state: RegistrationState?,
            message: String
        ) {
            updateSipIconResource()
        }

        override fun onNetworkReachable(core: Core, reachable: Boolean) {
            val address = addressWaitingNetworkToBeCalled.orEmpty()
            if (reachable && address.isNotEmpty()) {
                val now = System.currentTimeMillis()
                if (now - timeAtWitchWeTriedToCall > 1000) {
                    Log.e("[Dialer] More than 1 second has passed waiting for network, abort auto call to $address")
                    enteredUri.value = address
                } else {
                    Log.i("[Dialer] Network is available, continue auto call to $address")
                    coreContext.startCall(address)
                }

                addressWaitingNetworkToBeCalled = null
                timeAtWitchWeTriedToCall = 0
            }
        }

//        override fun onVersionUpdateCheckResultReceived(
//            core: Core,
//            result: VersionUpdateCheckResult,
//            version: String?,
//            url: String?
//        ) {
//            if (result == VersionUpdateCheckResult.NewVersionAvailable) {
//                Log.i("[Dialer] Update available, version [$version], url [$url]")
//                if (url != null && url.isNotEmpty()) {
//                    updateAvailableEvent.value = Event(url)
//                }
//            }
//        }
    }

    init {
        coreContext.core.addListener(listener)
        coreContext.core.defaultAccount?.addListener(accountListener)

        enteredUri.value = ""
        atLeastOneCall.value = coreContext.core.callsNb > 0
        transferVisibility.value = false

        showSwitchCamera.value = coreContext.showSwitchCameraButton()

        mSipLine.value = coreContext.core.defaultAccount?.params?.identityAddress?.username
        mCallLogsState.value = 0
        mCallLogsListData.value = ArrayList<Module_Phone_GroupedCallLogData>()
        mOutgoingCallLogsListData.value = ArrayList<Module_Phone_GroupedCallLogData>()
        mCallLogsSearchListData.value = ArrayList<Module_Phone_GroupedCallLogData>()
        mShowDialerPlate.value = true
        updateSipIconResource()
    }

    fun updateSipIconResource() {
        mSipIconResource.value = when (coreContext.core.defaultAccount?.state) {
            RegistrationState.Ok -> R.mipmap.sip_line_green
            RegistrationState.Failed -> R.mipmap.sip_line_red
            RegistrationState.Progress -> R.mipmap.sip_line_yellow
            else -> R.mipmap.sip_line_gray
        }
        val isRegisterEnabled = coreContext.core.defaultAccount?.params?.isRegisterEnabled
        isRegisterEnabled?.run {
            if (!isRegisterEnabled) { // 账号未启用更新未连接图标
                mSipIconResource.value = R.mipmap.sip_line_gray
            }
        }

        mSipIconContentDescription.value = when (coreContext.core.defaultAccount?.state) {
            RegistrationState.Ok -> context.getString(R.string.status_connected)
            RegistrationState.Progress -> context.getString(R.string.status_in_progress)
            RegistrationState.Failed -> context.getString(R.string.status_error)
            else -> context.getString(R.string.status_not_connected)
        }

        if (coreContext.core.defaultAccount?.state == RegistrationState.Failed) {
            val error = when (coreContext.core.defaultAccount?.errorInfo?.protocolCode) {
                100 -> context.getString(R.string.status_error_code_info_100)
                500 -> context.getString(R.string.status_error_code_info_500)
                503 -> context.getString(R.string.status_error_code_info_503)
                504 -> context.getString(R.string.status_error_code_info_504)
                else -> {
                    coreContext.core.defaultAccount?.errorInfo?.protocolCode.toString()
                }
            }

            if (!TextUtils.isEmpty(error)) {
                mSipIconContentDescription.value = "${mSipIconContentDescription.value} , $error"
            }
        }
    }

    override fun onCleared() {
        coreContext.core.removeListener(listener)
        coreContext.core.defaultAccount?.removeListener(accountListener)

        super.onCleared()
    }

    // This is to workaround the cursor being set to the start when pressing a digit
    fun onBeforeUriChanged(editText: EditText, count: Int, after: Int) {
        enteredUriCursorPosition = editText.selectionEnd
        enteredUriCursorPosition += after - count
    }

    fun onAfterUriChanged(editText: EditText, editable: Editable?) {
        val newLength = editable?.length ?: 0
        if (newLength <= enteredUriCursorPosition) enteredUriCursorPosition = newLength
        if (enteredUriCursorPosition < 0) enteredUriCursorPosition = 0
        editText.setSelection(enteredUriCursorPosition)
    }

    fun onFocusUriChanged(editText: EditText) {
        mShowDialerPlate.value = true
        val inputMethodManager =
            context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
        inputMethodManager?.hideSoftInputFromWindow(editText.windowToken, 0)

        val timer: Timer = Timer()
        timer.schedule(
            object : TimerTask() {
                override fun run() {
                    val inputMethodManager =
                        context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
                    inputMethodManager?.hideSoftInputFromWindow(editText.windowToken, 0)
                }
            },
            50
        )
    }

    fun updateShowVideoPreview() {
        val videoPreview = corePreferences.videoPreview
        showPreview.value = videoPreview
        coreContext.core.isVideoPreviewEnabled = videoPreview
    }

    fun eraseLastChar() {
        enteredUri.value = enteredUri.value?.dropLast(1)
    }

    fun eraseChar() {
        if (mDialerEditText.value?.selectionStart == null) {
            enteredUriCursorPosition = 0
        } else {
            enteredUriCursorPosition = mDialerEditText.value?.selectionStart!!
        }
        if (enteredUriCursorPosition < 0) enteredUriCursorPosition = 0

        val sb: StringBuilder = StringBuilder(enteredUri.value)
        try {
            sb.deleteAt(enteredUriCursorPosition - 1)
        } catch (ioobe: IndexOutOfBoundsException) {
        }
        enteredUri.value = sb.toString()
    }

    fun eraseAll(): Boolean {
        enteredUri.value = ""
        return true
    }

    fun directCall(to: String) {
        if (coreContext.core.isNetworkReachable) {
            coreContext.startCall(to)
        } else {
            Log.w("[Dialer] Network isnt't reachable at the time, wait for network to start call (happens mainly when app is cold started)")
            timeAtWitchWeTriedToCall = System.currentTimeMillis()
            addressWaitingNetworkToBeCalled = to
        }
    }

    fun startCall() {
        var addressToCall = enteredUri.value.orEmpty()

        if (addressToCall.isNotEmpty()) {
            coreContext.startCall(addressToCall)
            eraseAll()
        } else {
            setLastOutgoingCallAddress()
        }
    }

    fun transferCall(): Boolean {
        var addressToCall = enteredUri.value.orEmpty()
        addressToCall = addressToCall.replace("*", ".", true)
        return if (addressToCall.isNotEmpty()) {
            coreContext.transferCallTo(addressToCall)
            eraseAll()
            true
        } else {
            setLastOutgoingCallAddress()
            false
        }
    }

    fun switchCamera() {
        coreContext.switchCamera()
    }

    private fun setLastOutgoingCallAddress() {
        coreContext.callErrorMessageResourceId.value =
            Module_Phone_Event(context.getString(R.string.toast_input_phone_number))
//        val callLog = coreContext.core.lastOutgoingCallLog
//        if (callLog != null) {
//            enteredUri.value = LinphoneUtils.getDisplayableAddress(callLog.remoteAddress)
//        }
    }
}
